/*
 * @Author: silence
 * @Date: 2022-01-28 15:08:10
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-12-15 09:59:23
 * @Description: 文件头部注释
 * @FilePath: /phpCenter/arcade_games_flutter/lib/utils/pushMessage/PushMessageUtils.dart
 */
import 'dart:convert';
import 'dart:io';

import 'package:ems_neutral_app/pages/Mine/Fault/FaultPage.dart';
import 'package:flutter/widgets.dart';
import 'package:sil_utils_package/sil_utils_package.dart';
import '../../../config/AppInfo.dart';
import '../../../utils/router/ARouter.dart';
import '../../../utils/string/StringConstant.dart';
import 'package:jpush_flutter/jpush_flutter.dart';

import '../../../bloc/userbloc/user_bloc.dart';
import '../../common/module/WebViewPage/WebViewPage.dart';
// import '../../../entities/PushMessageEntity.dart';
import '../../config/ThirdConfig.dart';
import '../../main.dart';
import '../eventBus/eventBus.dart';

class PushMessageUtils {
  static JPush _jPush = JPush();

  /**
   * @description: 初始化
   * @param {*}
   * @return {*}
   */
  static setup() {
    // 通知回调方法
    _jPush.addEventHandler(
      // 接收通知回调方法。
      onReceiveNotification: (Map<String, dynamic> message) async {
        print("flutter onReceiveNotification: $message");
        handlerPushMessage(message);
      },

      // 点击通知栏回调方法。
      onOpenNotification: (Map<String, dynamic> message) async {
        print("点击通知栏回调方法: $message");
        handlerPushMessage(message);
      },

      // 接收自定义消息回调方法。
      onReceiveMessage: (Map<String, dynamic> message) async {
        // print("flutter onReceiveMessage: $message");
        // handlerPushMessage(message);
      },
    );

    _jPush.setup(
      appKey: ThirdConfig.JpushAppId,
      channel: Platform.isIOS ? "App Store" : "Android channel",
      production: true, // 0（默认值）表示采用的是开发证书，1 表示采用生产证书发布应用。
      debug: true, // 设置是否打印 debug 日志
    );

    // 申请推送权限
    if (Platform.isIOS) {
      _jPush.applyPushAuthority(
          new NotificationSettingsIOS(sound: true, alert: true, badge: true));
    }

    // 获取设备id
    registrationId();

    // 去掉角标
    _jPush.setBadge(0).then((map) {});
  }

  // 通知授权是否打开
  static Future<bool> isNotificationEnabled() async {
    return await _jPush.isNotificationEnabled();
  }

  // 得到启动app消息
  static launchAppNotification() {
    _jPush.getLaunchAppNotification().then((map) {
      print("flutter getLaunchAppNotification:$map");

      // 需要判断是否登录
      if (UserBlocTool.isLogin() == false) {
        bus.on(StringConstant.UserLoginInEvent, (arg) {
          // 刷新
          handlerPushMessage(map);
        });
      } else {
        handlerPushMessage(map);
      }
    });
  }

  /**
   * @description: 注册设备id、添加事件
   * @param {*}
   * @return {*}
   */
  static registrationId() {
    try {
      _jPush.getRegistrationID().then((rid) {
        AppInfo.registrationId = rid;
        print("flutter get registration id : $rid");
      });
    } catch (e) {
      print('getRegistrationID:$e');
    }
  }

  /**
   * @description: 处理推送消息
   * @param message 推送消息
   * @return {*}
   */
  static handlerPushMessage(dynamic value) async {
    SilLog.v({"handlerPushMessage": value});

    // 去掉角标
    _jPush.setBadge(0).then((map) {});

    if (value == null || value['extras'] == null) {
      return;
    }

    dynamic map;

    if (Platform.isAndroid) {
      var tempMap = value['extras'];
      if (tempMap.containsKey("cn.jpush.android.EXTRA")) {
        map = json.decode(tempMap["cn.jpush.android.EXTRA"].toString());
      }
    } else {
      map = value['extras'];
    }

    // PushMessageEntity message = PushMessageEntity();
//
    // if (map.containsKey('title')) {
    // message.title = map['title'];
    // }
//
    // if (map.containsKey('content')) {
    // message.content = map['content'];
    // }
//
    // if (map.containsKey('url')) {
    // message.url = map['url'];
    // }
//
    // if (map.containsKey('id')) {
    // if (map['id'] is String) {
    // message.id = int.parse(map['id']);
    // } else {
    // message.id = map['id'];
    // }
    // }
//
    // if (map.containsKey('type')) {
    // if (map['type'] is String) {
    // message.type = int.parse(map['type']);
    // } else {
    // message.type = map['type'];
    // }
    // }
    //

    // 这里简单粗暴处理，延迟直接跳转到故障统计列表
    // Future.delayed(Duration(milliseconds: 2000)).then((value) =>
    //     ARoute.gotoPage(navigatorKey.currentState!.context, FaultPage()));
  }

  // 根据类型做不同处理
  // static void gotoPage(PushMessageEntity message,
  // {bool atMessageCenter = false}) async {
  // 获取当前的context
  // BuildContext context = navigatorKey.currentState!.context;
  // int? msgType = message.type;
  // switch (msgType) {
  // case 16: // (课程购买成功通知)  课程详情      暂时跳转到已购课程  //todo:yes
  // {
  // ARoute.gotoPage(context, BuyedCourceTab());
  // }
  // break;
  // default:
  // {
  // 其他情况
  // 如果有url，就调到url
  // if (!SilTools.stringIsEmpty(message.url)) {
  // Map<String, dynamic> map = Map();
  // String url = message.url!;
  // if (map.containsKey('uid')) url = url + '?uid=' + map['uid'];
//
  // ARoute.gotoPage(
  // context,
  // WebViewPage(
  // url,
  // title: message.title,
  // ));
  // }
  // }
  // }
  // }
}
